<template>
  <div id='BacDescOption'>
    <Breadcrumb content='描述性结果' />
    <div class='bodyContent'>
      <Splitpanes class='area'>
        <Pane size='60'>
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input type='search' v-model='form.keyvalue' clearable class='vxeInputSearch' @search-click='findList' @clear='findList' @keyup.enter.native='findList' placeholder='关键字查询'></vxe-input>
              <vxe-button type='text' class='button-blue' @click='findList' icon='vxe-icon-refresh' :loading='loading'>刷新</vxe-button>
              <vxe-button type='text' class='button-blue' @click='addBacDescOption' icon='vxe-icon-add'>新增</vxe-button>
              <vxe-button type='text' class='button-red' @click='deleteBacDescOption' icon='vxe-icon-delete'>删除</vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-sort" content="从标准库创建" @click="staDataSync"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class='tableBox'>
            <vxe-table ref='tableRef' border='inner' align='left' class='mytable-scrollbar' :loading='loading' height='auto' :data='tableData' :row-config='{ isCurrent: true }' :column-config='{ resizable: true }' show-overflow keep-source :scroll-y='{ enabled: true }' @current-change='tableCellClick' :menu-config='menuConfig' @menu-click='contextMenuClickEvent'>
              <vxe-column type='checkbox' width='26'></vxe-column>
              <vxe-column type='seq' title='#' width='30'></vxe-column>
              <vxe-column field='optNo' title='编号' width='120'> </vxe-column>
              <vxe-column field='optNa' title='名称' width='300'> </vxe-column>
              <vxe-column field='germNo' title='细菌编号' width='120'> </vxe-column>
              <vxe-column field='germNa' title='细菌名称' width='120'> </vxe-column>
              <vxe-column field='inputCode' title='助记符'> </vxe-column>
              <vxe-column field='seq' title='排序码' width='90'> </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size='40'>
          <Splitpanes horizontal>
            <Pane size='100'>
              <BacDescOptionForm ref='BacDescOptionFormRef' :currentRow='currentRow' @findListData='findList' />
            </Pane>
          </Splitpanes>
        </Pane>
      </Splitpanes>

      <el-drawer v-model="showStaData" title="模板标准库同步" direction="rtl" size="50%" destroy-on-close="true">
        <vxe-button type="text" class="button-blue" icon="vxe-icon-copy" style="margin-left:5px;" content="复制" @click="staDataInsert"></vxe-button>
        <vxe-table ref="staTableRef" border="inner" align="left" class="mytable-scrollbar" :loading="showLoading" height="95%" :data="staTableData" :row-config="{ isCurrent: true, isHover: true }" :height="tableHeight" :column-config="{ resizable: true }" resizable show-overflow>
          <vxe-column type="checkbox" fixed="left" width="30"></vxe-column>
          <vxe-column field='optNo' title='编号'> </vxe-column>
          <vxe-column field='optNa' title='名称'> </vxe-column>
          <vxe-column field="seq" title="顺序" width="50">
            <template #default="{ row }">
              <span>{{ row.seq }}</span>
            </template>
          </vxe-column>
        </vxe-table>
      </el-drawer>

    </div>
  </div>
</template>

<script lang='ts' setup>
/**引入组件区 ==========*/
import Breadcrumb from '@/components/Breadcrumb.vue'; /**面包屑*/
import { reactive, ref, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';
import XEClipboard from 'xe-clipboard';
import BacDescOptionForm from './BacDescOptionForm.vue';

/**全局变量定义区 ==========*/
let { proxy }: any = getCurrentInstance();
/**左侧表格 */
const loading = ref(false); /**刷新+表格加载*/
const form = reactive({ keyvalue: '' }); /**根据关键字查询*/
const tableRef = ref<VxeTableInstance<RowVO>>(); /**表格ref标记*/
const tableData = reactive([]); /**表格数据*/

let showStaData = ref(false);
let staTableRef = ref(null);
let staTableData = reactive([]);
let showLoading = ref(false); //刷新+表格加载

/**右侧表单*/
const BacDescOptionFormRef = ref<InstanceType<typeof BacDescOptionForm>>();
let currentRow: any = reactive({ id: '', code: '' });

/**vxe-table 表格右击属性*/
const menuConfig = reactive<VxeTablePropTypes.MenuConfig<RowVO>>({
  header: {
    options: [
      [
        { code: 'hideColumn', name: '隐藏列', disabled: false },
        { code: 'showAllColumn', name: '取消所有隐藏列', disabled: false }
      ]
    ]
  },
  body: {
    options: [
      [
        { code: 'copy', name: '复制', prefixIcon: 'vxe-icon-copy', disabled: false },
        { code: 'reload', name: '刷新', disabled: false },
        { code: 'remove', name: '删除', disabled: false },
        { code: 'save', name: '保存', prefixIcon: 'vxe-icon-save', disabled: false }
      ]
    ]
  },
  visibleMethod({ options, column }) {
    const isDisabled = !column;
    options.forEach((list) => {
      list.forEach((item) => {
        item.disabled = isDisabled;
      });
    });
    return true;
  }
});

/**方法定义区 =============*/
onMounted(() => {
  findList(); /**获取描述性结果表格数据*/
});

/**获取 描述性结果表格数据*/
const findList = () => {
  loading.value = true;
  tableData.length = 0; /**放入数据前清空数据*/
  const url = '/api/bac/bac-desc-option/findBacDescOptionList';
  proxy.$http
    /**注意此处的数据条数*/
    .get(url, { keyWords: form.keyvalue })
    .then(async (res: any) => {
      tableData.push(...res.data);
      loading.value = false;
      if (res && res.data && res.data.length > 0) {
        tableCellClick({ row: res.data[0] });
        const $table = tableRef.value;
        if ($table) {
          //currentRow.id = '';
          await $table.setCurrentRow(res.data[0]);
        }
      }
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('获取描述性结果列表数据异常', VxeNotifyType.error);
    });
};

/**新增描述性结果*/
async function addBacDescOption() {
  (proxy.$refs.tableRef as any).clearCurrentRow();
  BacDescOptionFormRef.value?.addNew((e) => {
    //todo
  });
}

/**保存描述性结果*/
function saveBacDescOption() {
  BacDescOptionFormRef.value?.saveForm((e) => {
    // findList();
  });
}

/**删除描述性结果*/
async function deleteBacDescOption() {
  const arr = await tableRef.value?.getCheckboxRecords(true);
  if (!(arr && arr.length > 0 && arr[0])) {
    VxeMessage('请勾选要删除的描述性结果', VxeNotifyType.info);
    return;
  } else if (arr.length > 1) {
    VxeMessage('一次只可选择删除一条数据', VxeNotifyType.info);
    return;
  } else {
    proxy
      .$confirm('确定删除选中数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        const url = '/api/bac/bac-desc-option/deleteBacDescOption';
        const arr = await tableRef.value?.getCheckboxRecords(true);
        if (arr && arr.length > 0 && arr[0]) {
          proxy.$http
            .post(url, arr[0])
            .then((res: any) => {
              if (res.status.code === 1) {
                VxeMessage('删除描述性结果成功', VxeNotifyType.success);
                findList();
                BacDescOptionFormRef.value?.clearFormData();
              } else {
                VxeMessage('删除描述性结果失败', VxeNotifyType.error);
              }
            })
            .catch((err: any) => {
              // VxeMessage('删除描述性结果异常', VxeNotifyType.error);
            });
        }
      });
  }
}

// 表格右击菜单项
const contextMenuClickEvent: VxeTableEvents.MenuClick<RowVO> = ({ menu, row, column }) => {
  const $table = tableRef.value;
  if (table) {
    switch (menu.code) {
      case 'hideColumn':
        $table.hideColumn(column);
        break;
      case 'showAllColumn':
        $table.resetColumn(true);
        break;
      case 'copy':
        if (XEClipboard.copy((row as any)[column.field])) {
          VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
        }
        break;
      case 'reload':
        findList();
        break;
      case 'insertAt':
        $table.insertAt({}, row || -1).then(({ row }) => {
          $table.setEditCell(row, column || 'name');
        });
        break;
      case 'remove':
        $deleteBacDescOption();
        break;
      case 'save':
        saveBacDescOption();
        break;
    }
  }
};

/**表格选中当前行*/
function tableCellClick({ row }) {
  Object.assign(currentRow, row);
  proxy.$forceUpdate();
}

function staDataSync() {
  staTableData.length = 0; //放入数据前清空数据
  const url = '/api/sta/sta-desc-option/findBacDescOptionList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { searchValue: form.keyvalue } })
    .then(async (res: any) => {
      staTableData.push(...res.data);
    })
    .catch((err: any) => {
      showLoading.value = false;
      VxeMessage('获取模板数据异常', VxeNotifyType.error);
    });

  showStaData.value = true;
}

async function staDataInsert() {
  let arr = await staTableRef.value?.getCheckboxRecords(true);
  if (!(arr.length > 0)) {
    VxeMessage('请勾选要同步的数据', VxeNotifyType.info);
  } else {
    const url = '/api/bac/bac-desc-option/updateBatchBacDescOption';
    proxy.$http
      .post(url, { bacDescOptionList: arr })
      .then((res: any) => {
        showStaData.value = false;
        findList(); // 获取检验仪器表格数据
        VxeMessage('同步成功!', VxeNotifyType.success);
      })
      .catch((err: any) => {
        showStaData.value = false;
        VxeMessage(err, VxeNotifyType.error);
      });
  }
}
</script>
<style lang='scss' scoped>
#BacDescOption {
  width: 100%;
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .tableBox {
        height: calc(100% - 40px);
      }
    }
  }
}
</style>